package com.ywq.app.web.mvc.auction;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ywq.app.BidThread;
import com.ywq.app.biz.ArtAuctionBiz;
import com.ywq.app.biz.ArtPicBiz;
import com.ywq.app.biz.AuxContentBiz;
import com.ywq.app.biz.MemberBiz;
import com.ywq.app.domain.ArtActivityMember;
import com.ywq.app.domain.ArtAuction;
import com.ywq.app.domain.ArtClass;
import com.ywq.app.domain.ArtOrders;
import com.ywq.app.domain.ArtPic;
import com.ywq.app.domain.ArtReminder;
import com.ywq.app.domain.AuctionSo;
import com.ywq.app.domain.Channel;
import com.ywq.app.domain.Content;
import com.ywq.app.domain.Member;
import com.ywq.app.domain.OnLineUserListener;
import com.ywq.app.domain.PicBidLog;
import com.ywq.common.constant.Constant;
import com.ywq.common.constant.PageSize;
import com.ywq.common.exception.AppBusinessException;
import com.ywq.common.page.PageModel;
import com.ywq.common.util.Common;

@Controller
public class ArtAuctionController {
	private final static Logger logger = LoggerFactory
			.getLogger(ArtAuctionController.class);
	@Autowired
	private ArtPicBiz artPicBiz;
	@Autowired
	private ArtAuctionBiz artAuctionBiz;
	@Autowired
	private BidThread bidThread;
	@Autowired
	private MemberBiz memberBiz;
	@Autowired
	private AuxContentBiz auxContentBiz;

	// 拍卖列表页
	@RequestMapping(value = "/auction.htm", method = RequestMethod.GET)
	public String auction(Integer page, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			if (page == null) {
				page = 1;
			}
			PageModel pageAuction = artAuctionBiz.getArtAuctionList(page);
			request.setAttribute("pageAuction", pageAuction);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return "artOne/auction/auctionlb";

	}

	// art
	@RequestMapping(value = "/reminder.htm", method = RequestMethod.POST)
	public String reminder(ArtReminder artReminder, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			// OnLineUserListener onLineUserListener = (OnLineUserListener)
			// request.getSession().getAttribute("onlineUser");event_id
			if (Common.notEmptyStr(artReminder.getEmail())) {
				artReminder.setType("auction");
				artAuctionBiz.insertArtReminder(artReminder);
				pw = response.getWriter();
				pw.print("success");
			} else {
				pw = response.getWriter();
				pw.print("error");
			}
		} catch (Exception e) {
			pw = response.getWriter();
			pw.print("error");
			if (logger.isErrorEnabled()) {
				logger.error("auction failure.", e);
			}
		}
		return null;
	}
	@RequestMapping(value = "/reminderMade.htm", method = RequestMethod.POST)
	public String reminderMade(ArtReminder artReminder, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			if (Common.notEmptyStr(artReminder.getEmail())) {
				artReminder.setType("made");
				artAuctionBiz.insertArtReminder(artReminder);
				pw = response.getWriter();
				pw.print("success");
			} else {
				pw = response.getWriter();
				pw.print("error");
			}
		} catch (Exception e) {
			pw = response.getWriter();
			pw.print("error");
			if (logger.isErrorEnabled()) {
				logger.error("auction failure.", e);
			}
		}
		return null;
	}
	// 展示
	@RequestMapping(value = "/aucart.htm", method = RequestMethod.GET)
	public String aucart(String id,AuctionSo auctionSo,String seqtype,String seq,HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			OnLineUserListener onLineUserListener = (OnLineUserListener) request.getSession().getAttribute("onlineUser");
			//true 小到大
			//false从大到小
			if(seqtype!=null){
				if("myPrice".equals(seqtype) || "myLove".equals(seqtype)){
					auctionSo.setMemberId(onLineUserListener.getMember().getId());
				}
				if(seq==null || "".equals(seq)){
					seq="true";
				}else{
					if("true".equals(seq)){
						seq="false";
					}else if("false".equals(seq)){
						seq="true";
					}
				}
			}
			ArtAuction artAuction = artAuctionBiz.getInAuctionByAucId(id,auctionSo,seqtype,seq);
			//查询拍卖公告
			List<Content> noticeList = auxContentBiz.getRoomByChannel("notice", 1);
			if(noticeList.size()>0){
				request.setAttribute("notice", noticeList.get(0));
			}
			//查询真品、延时、保证金
			Channel realArt =auxContentBiz.getChannelByMark("realArt");
			Channel delay =auxContentBiz.getChannelByMark("delay");
			Channel securityMoney =auxContentBiz.getChannelByMark("securityMoney");
			request.setAttribute("realArt",realArt);
			request.setAttribute("delay",delay);
			request.setAttribute("securityMoney",securityMoney);
			PicBidLog sumBidPirce = artAuctionBiz.getSumBidPirceLog(id);
			// 查看拍卖官内所有最新总出价
			// PicBidLog bid= artPicBiz.getPicBidLogByPicId(id);
			// request.setAttribute("bid", bid);
			Date d = new Date();
			long longtime = d.getTime();
			long longtimeSever = longtime / 1000;
			String endDateString = artAuction.getEndDate() + " " + artAuction.getEndTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				Date sDate = sdf.parse(endDateString);
				long longEnd = sDate.getTime();
				long longEndWeb = longEnd / 1000;
				request.setAttribute("longEndWeb", longEndWeb);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			request.setAttribute("longtimeSever", longtimeSever);
			request.setAttribute("pageAuction", artAuction);
			request.setAttribute("sumBidPirce", sumBidPirce);
			List<ArtClass> auctionClass=artPicBiz.getChildById("0", Constant.PIC_AUCTION_CLASS);
			request.setAttribute("auctionClass", auctionClass);
			request.setAttribute("id", id);
			request.setAttribute("auctionSo", auctionSo);
			request.setAttribute("seq", seq);
			request.setAttribute("seqtype", seqtype);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return "artOne/auction/auction";

	}

	// 刷新
	@RequestMapping(value = "/event.htm", method = RequestMethod.GET)
	public String event(String id, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			PicBidLog sumBidPirce = artAuctionBiz.getSumBidPirceLog(id);
			pw = response.getWriter();
			pw.print(JSONObject.fromObject(sumBidPirce));
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/bidArt.htm", method = RequestMethod.POST)
	public String bidArt(String id, String auctionId, String price, HttpServletRequest request, HttpServletResponse response) throws IOException {
			OnLineUserListener onLineUserListener = (OnLineUserListener) request.getSession().getAttribute("onlineUser");
			Member memberLine=null;
				try {
						memberLine =memberBiz.getMemberById(onLineUserListener.getMember().getId());
					} catch (AppBusinessException e1) {
				}
		
		if (!Common.empty(memberLine) && !"".equals(memberLine.getArtAccount())){
				if(memberLine.getArtAccount() >=PageSize.MEMBER_ACCOUNT && !"".equals(memberLine.getIsAccount())){
				if (memberLine.getIsAccount()) {
					response.setContentType("text/html; charset=UTF-8");
					PrintWriter pw = null;
					pw = response.getWriter();
					ArtPic artPicIsJoin = new ArtPic();
					artPicIsJoin.setError("join");
					pw.print(JSONObject.fromObject(artPicIsJoin));
				} else {
				response.setContentType("text/html; charset=UTF-8");
				PrintWriter pw = null;
				SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Map<String, Object> map = new HashMap<String, Object>();
				String nowTime = f.format(new Date());
				map.put("memberId", onLineUserListener.getMember().getId());
				map.put("bidTime", nowTime);
				map.put("bidPrice", price);
				map.put("id", id);
				try {
					// 出价.valueOf
					float bidPrice = Float.valueOf(price);
					// 艺术作品信息
					ArtPic artPic = artPicBiz.getArtPic(id);
					if (artPic != null) {
						if (!artPic.getIsForward()) {
							if (bidPrice >= artPic.getPriceMax()
									&& bidPrice > artPic.getPrice()) {
								// 添加出价log
								PicBidLog newBid = new PicBidLog();
								newBid.setMemberId(onLineUserListener
										.getMember().getId());
								newBid.setBidPrice(bidPrice);
								newBid.setPicId(id);
								newBid.setAuctionId(auctionId);
								artPicBiz.insertPicBidLog(newBid);
								// 一口价 直接成交 下订单
								ArtOrders orders = new ArtOrders();
								orders.setMemberId(onLineUserListener
										.getMember().getId());
								orders.setTypeId(id);
								orders.setType("auction");
								orders.setSucPrice(bidPrice);
								artAuctionBiz.insertArtOrders(orders);
								artPic.setError("s");
							} else if (bidPrice > artPic.getPrice()
									&& bidPrice < artPic.getPriceMax()) {
								// 查看最高价
								PicBidLog bid = artPicBiz.getPicBidLogByPicId(
										id, auctionId);
								if (bid != null) {
									double maxPrice = bid.getBidPrice();
									if (maxPrice >= bidPrice) {
										// 出价低
										artPic.setError("l");
									} else if (bidPrice > maxPrice) {
										// 添加出价log
										PicBidLog newBid = new PicBidLog();
										newBid.setMemberId(onLineUserListener
												.getMember().getId());
										newBid.setBidPrice(bidPrice);
										newBid.setPicId(id);
										newBid.setAuctionId(auctionId);
										artPicBiz.insertPicBidLog(newBid);
										// 锁定账号
										// 加入线程
										bidThread.setBidArt(map);
										artPic.setError("thread");
									}
								} else {
									// 添加出价log
									PicBidLog newBid = new PicBidLog();
									newBid.setMemberId(onLineUserListener
											.getMember().getId());
									newBid.setBidPrice(bidPrice);
									newBid.setPicId(id);
									newBid.setAuctionId(auctionId);
									artPicBiz.insertPicBidLog(newBid);
									// 锁定账号
									// 加入线程
									bidThread.setBidArt(map);
									artPic.setError("thread");
								}
							} else {
								// 出价低
								artPic.setError("l");
							}
							pw = response.getWriter();
							pw.print(JSONObject.fromObject(artPic));
						} else {
							ArtPic artPicIsSale = new ArtPic();
							artPicIsSale.setError("lasat");
							pw = response.getWriter();
							pw.print(JSONObject.fromObject(artPicIsSale));
						}
					} else {
						ArtPic artPicNull = new ArtPic();
						artPicNull.setError("empty");
						pw = response.getWriter();
						pw.print(JSONObject.fromObject(artPicNull));
					}
				} catch (AppBusinessException e) {
					e.printStackTrace();
				}
			}
		
		}else{
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter pw = null;
			pw = response.getWriter();
			ArtPic artPicNull = new ArtPic();
			artPicNull.setError("nohaveAccount");
			pw = response.getWriter();
			pw.print(JSONObject.fromObject(artPicNull));
		}
		}
		return null;
	}

	//

	@RequestMapping(value = "/auctionpic.htm", method = RequestMethod.GET)
	public String auctionpic(String id, String aid, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			ArtPic artPic = artPicBiz.getArtPic(id);
			List<PicBidLog> listLog = artAuctionBiz.getLogListBid(id);
			ArtAuction pageAuction = artAuctionBiz.getInAuctionByAucId(aid,null,null,null);

			Date d = new Date();
			long longtime = d.getTime();
			long longtimeSever = longtime / 1000;
			String endDateString = pageAuction.getEndDate() + " "
					+ pageAuction.getEndTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				Date sDate = sdf.parse(endDateString);
				long longEnd = sDate.getTime();
				long longEndWeb = longEnd / 1000;
				request.setAttribute("longEndWeb", longEndWeb);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			request.setAttribute("longtimeSever", longtimeSever);
			request.setAttribute("pageAuction", pageAuction);
			request.setAttribute("listLogCount", listLog.size());
			request.setAttribute("listLog", listLog);
			request.setAttribute("artPic", artPic);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return "artOne/auction/auctionPic";

	}

	public static void main(String str[]) {
		/*String str1 = new String("abcde");
		String str2 = new String("abcde");
		String str3 = new String("abcde");
		String str4 = new String("abcde");
		String str5 = new String("abcde");
		List list = new ArrayList();
		list.add(str1);
		list.add(str2);
		list.add(str3);
		list.add(str4);
		list.add(str5);

		System.out.println("list.size()=" + list.size());
		for (int i = 0; i < list.size(); i++) {
			if (((String) list.get(i)).startsWith("abcde")) {
				list.remove(i);
			}
		}
		System.out.println("after remove:list.size()=" + list.size());*/
	}
	//首页底部
	@RequestMapping(value = "/showAuction.htm", method = RequestMethod.GET)
	public String show(String remark,HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			List<Content> contentList = auxContentBiz.getRoomByChannel(remark, 1);
			if(contentList.size()>0){
				Content content =contentList.get(0);
				request.setAttribute("content", content);
			}
			/*List<Content> realArt = auxContentBiz.getRoomByChannel("realArt", 1);
			request.setAttribute("realArt", realArt.get(0));
			List<Content> delay = auxContentBiz.getRoomByChannel("delay", 1);
			request.setAttribute("delay", delay.get(0));
			List<Content> securityMoney = auxContentBiz.getRoomByChannel("securityMoney", 1);
			request.setAttribute("securityMoney", securityMoney.get(0));*/
			//request.setAttribute("rightUpList", rightUpList);
			request.setAttribute("comcon", "show");
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return "artOne/common/comcon";
		
	}
}
